/**
 * Copyright 2021 Inc.
 **/
package com.myz.distributed.transaction.rocketmq.common;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author maoyz0621 on 2021/5/21
 * @version v1.0
 */
@Service
public class TransactionService {

    @Resource
    UserRepository userRepository;

    @Resource
    TransferRecordRepository transferRecordRepository;

    @Transactional(rollbackFor = Exception.class)
    public boolean doTransfer(Long fromUserId, Long toUserId, Long changeMoney, String businessNo, String transactionId) throws Exception {
        //插入转账记录明细 businessNo加唯一建 做去重操作 防止消息重试发送 导致本地事务多次执行 重复扣钱
        //转账记录中 记录 消息事务transactionId 用于后续状态回查
        TransferRecordEntity transferRecord = new TransferRecordEntity();
        transferRecord.setFromUserId(fromUserId);
        transferRecord.setChangeMoney(changeMoney);
        transferRecord.setTransactionId(transactionId);
        transferRecord.setToUserId(toUserId);
        transferRecord.setRecordNo(businessNo);
        transferRecordRepository.save(transferRecord);

        // 执行A扣钱操作
        // update user set money = money - #{money} where id = #{userId} and money >= #{money}
        int result = userRepository.reduceMoney(fromUserId, changeMoney);
        if (result <= 0) {
            throw new RuntimeException("账户余额不足");
        }
        System.out.println("转账成功,fromUserId:" + fromUserId + ",toUserId:" + toUserId + ",money:" + changeMoney);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean increaseMoney(Long toUserId, Long changeMoney) {
        userRepository.increaseMoney(toUserId, changeMoney);
        int i = 1 / 0;
        return true;
    }

    /**
     * 检查本地扣钱事务执行状态
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean checkTransferStatus(String transactionId) {
        //根据transactionId查询转账记录 有转账记录 标识本地事务执行成功 即A扣钱成功
        int count = transferRecordRepository.getTransferRecordEntitiesByTransactionId(transactionId);
        return count > 0;
    }

}